package org.ruoyi.common.dhuman.utils.v1;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.kevinsawicki.http.HttpRequest;
import org.ruoyi.common.core.utils.StringUtils;
import org.ruoyi.common.dhuman.utils.v1.vo.TTSVo;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

/**
 * <p>Name: TTS</p>
 * <p>Description: TTS</p>
 * <p>Author: Jelly</p>
 * <p>Date: 2022/4/11 11:00</p>
 **/
public class TTS {

	public TTS(String appid, String appSecret, String endpoint) {
		this.appid = appid;
		this.appSecret = appSecret;
		this.endpoint = endpoint;
	}

    public String appid;

    public String appSecret;

    public String endpoint;

    public String sign(int timestamp) {
        String serial = this.appid + timestamp + this.appSecret;

        String sign = DigestUtils.md5DigestAsHex(serial.getBytes(StandardCharsets.UTF_8));
        return "MD5 " + sign.toUpperCase();
    }

    public String doTTS(TTSVo requestVO) {
		if (StringUtils.isEmpty(requestVO.getText())) {
			return StringUtils.EMPTY;
		}

		if (StringUtils.isEmpty(requestVO.getVoice_name())) {
			requestVO.setVoice_name("xiaoya");
		}

        ObjectMapper objectMapper = new ObjectMapper();
        int timestamp = (int)(System.currentTimeMillis() / 1000L);
        try {
            String payload = objectMapper.writeValueAsString(requestVO);
			System.out.println("payload: " + payload);
            String sign = this.sign(timestamp);
            HttpRequest httpRequest = HttpRequest.post(this.endpoint)
                    .contentType("application/json", "utf-8")
                    .header("X-Deepsound-Appid", this.appid)
                    .header("X-Deepsound-Timestamp", timestamp)
                    .header("x-Deepsound-Sign", sign)
                    .send(payload);
			String response = httpRequest.body();
            System.out.println(response);
			return response;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

		return StringUtils.EMPTY;
    }
}
